package com.itlong.cloud.utils.node;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * <desc>
 *      Map转换帮助类。
 * </desc>
 *
 * @createDate 2017/11/23
 */
public class MapUtil {

    /**
     * <desc>
     *      将对象转换为Map。
     * <desc/>
     * @param  obj  对象
     * @param  t    true：包含null的key ，false不包含null的key
     * @return
     * @author Wecnhao.L
     * @createDate 2017/11/23
     */
    public static Map<String, Object> objectToMap(Object obj, boolean t) throws Exception {
        if(obj == null){
            return null;
        }
        Map<String, Object> map = new HashMap<>();
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            String key = property.getName();
            if (key.compareToIgnoreCase("class") == 0) {
                continue;
            }
            Method getter = property.getReadMethod();
            Object value = getter!=null ? getter.invoke(obj) : null;
            if(t){
                map.put(key, value);
            }else{
                if(value != null){
                    map.put(key, value);
                }
            }
        }

        return map;
    }

    /**
     * <desc>
     *      将map转换为对象。
     * <desc/>
     * @param  map  map对象
     * @param  beanClass    转换的对象
     * @return
     * @author Wecnhao.L
     * @createDate 2017/11/23
     */
    public static Object mapToObject(Map<String, Object> map, Class<?> beanClass) throws Exception {
        if (map == null){
            return null;
        }
        Object obj = beanClass.newInstance();
        BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor property : propertyDescriptors) {
            Method setter = property.getWriteMethod();
            if (setter != null && map.get(property.getName())!=null) {
                try {
                    setter.invoke(obj, map.get(property.getName()));
                }catch (Exception e){
                    setter.invoke(obj,Integer.valueOf(map.get(property.getName()).toString()));
                }
            }
        }
        return obj;
    }
}
